# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.

class ApplicationController < ActionController::Base
  # Pick a unique cookie name to distinguish our session data from others'
  session :session_key => '_contenid-os_session_id'

  # Be sure to include AuthenticationSystem in Application Controller instead
  include AuthenticatedSystem


  # If you want "remember me" functionality, add this before_filter to Application Controller
  #before_filter :login_from_cookie

  # Pone las variables para lo que se necesite a los lados.
  def prepare_layout
    if self.logged_in?
      if self.is_admin?
        # Ultimos instructores en hacer log in.
        @side_instructors = User.find(:all, :conditions => ['kind = ? AND last_login IS NOT NULL AND activation_code IS NULL', 'Instructor'], :order => 'last_login DESC', :limit => 7)
        # Ultimos administradores en hacer log in.
        @side_admins = User.find(:all, :conditions => ['kind = ? AND last_login IS NOT NULL AND activation_code IS NULL AND NOT login = ?', 'Admin', self.current_user.login], :order => 'last_login DESC', :limit => 5)
        # Ultimos estudiantes en hacer log in.
        @side_students = User.find(:all, :conditions => ['kind = ? AND last_login IS NOT NULL AND activation_code IS NULL', 'Student'], :order => 'last_login DESC', :limit => 15)
        # Lista de cursos
        @side_courses = Course.find(:all, :conditions => ['end_date > NOW() OR end_date IS NULL and NOT id = 1'], :order => 'end_date DESC', :limit => 7)
        #
        @side_events_days = self.current_user.courses.map { |c| c.events }.flatten.map { |e| e.due_date.to_date }

      else
        # Eventos personales: Eventos creados por uno mismo.
        now = Time.now
        @side_events_own = self.current_user.events.select { |c| c.expire_date > now }.sort { |a,b| a.expire_date <=> b.expire_date }[0,7]
        # Eventos de curso: Eventos relacionados con los cursos de uno
        @side_events_courses = self.current_user.courses.map { |c| c.events }.flatten.select { |c| c.expire_date > now }.sort { |a,b| a.expire_date <=> b.expire_date }[0,7]
        # Eventos de curso: Eventos relacionados con los cursos de uno
        @side_events_days = self.current_user.courses.map { |c| c.events }.flatten.map { |e| e.due_date.to_date }.select { |d| d.month == (params[:month] || now.month) }
        # Eventos globales: Eventos relacionados con el curso con id = 1.
        @side_events_global = Course.find_by_name('Eventos Globales').events.select { |c| c.expire_date > now }.sort { |a,b| a.expire_date <=> b.expire_date }
        if self.is_student?
          @side_courses = self.current_user.courses
        else
          @side_courses = self.current_user.created_courses + self.current_user.courses
        end
      end
    end
  end

  before_filter :prepare_layout

end
